import * as types from '../action-types';
import {AnyAction} from 'redux'
import * as profileAPI from '@/api/profile'
import { push } from 'connected-react-router';
import { RegisterPayload,LoginPayload,RegisterResult,LoginResult} from "@/typings/user";
import {message} from "antd";
import { setSession } from '@/utils/storage';

// 本文示例了 redux-promise 和 redux-thunk 的用法
export default {
  validate(): AnyAction {
    //发起判断当前用户是否登录的请求
    return {
      type: types.VALIDATE,
      payload: profileAPI.validate(), 
    };
  },

  register(values:RegisterPayload){
    return (dispatch:any)=>{
      (async function(){
        try{
          let result:any =await profileAPI.register(values);
          if(result.success){
            message.info("注册成功");
            dispatch(push("/login"));
          }
        }
        catch(err){
          message.error(err.response?err.response.data.message:err.message);
        }
      })()
    }
  },

  login(values:LoginPayload){
    return (dispatch:any)=>{
        (async ()=>{
           try{
             let result:any =await profileAPI.login(values);
             if(result.success){
                setSession("access_token",result.data.token);
                dispatch(push("/profile"));
             }
             else{
               message.error(result.message);
             }
           }catch(err){
            message.error(err.response?err.response.data.message:err.message);
           }
        })()
    }
  },

  logout(){ 
    return function(dispatch:any){
      sessionStorage.removeItem("access_token");
      dispatch({type:types.LOGOUT});
      dispatch(push("/login"))
    }
  },

  changeAvatar(avatar:string){
    return{
      type:types.CHANGE_AVATAR,
      payload:avatar,
    }
  }
}